class Relation < ActiveRecord::Base
  belongs_to :subject, :polymorphic => true
  belongs_to :object, :polymorphic => true
  belongs_to :user
  
  def self.add_relation_to_context(object,user,context_elements)
    context_elements.each do |context|
      subject = context.artifact
      relation = Relation.find(:first, :conditions => ['subject_id = ? AND object_id = ? AND user_id = ?',subject.id,object.id,user.id])
      if relation.nil? and subject.id != object.id
        relation = Relation.new
        relation.subject = subject
        relation.object = object
        relation.user = user
        relation.save!
      end
    end
  end
  
  def self.remove_relation_to_context(object,user, context_elements)
    context_elements.each do |context|
      subject = context.artifact
      relation = Relation.find(:first, :conditions => ['subject_id = ? AND object_id = ? AND user_id = ?',subject.id,object.id,user.id])
      relation.destroy unless relation.nil?
      relation = Relation.find(:first, :conditions => ['object_id = ? AND subject_id = ? AND user_id = ?',subject.id,object.id,user.id])
      relation.destroy unless relation.nil?
    end
  end
end
